import styles from "./auth.module.scss";
import { IconButton } from "./button";

import { useNavigate } from "react-router-dom";
import { Path } from "../constant";
import { useAccessStore } from "../store";
import Locale from "../locales";

import BotIcon from "../icons/bot.svg";
import { useEffect } from "react";
import { getClientConfig } from "../config/client";

import request from "../utils/request";
import Cookie from "js-cookie";

export function AuthPage() {
  const navigate = useNavigate();
  const accessStore = useAccessStore();

  const goHome = () => navigate(Path.Home);
  // const goChat = () => navigate(Path.Chat);

  const goChat = () => {
    console.log(accessStore.user, "code");

    request({
      url: "http://apibase-test.namelxf.com/v1/customer/login/password/login",
      data: {
        login_name: accessStore.user.login_name,
        password: accessStore.user.password,
      },
      method: "post",
    }).then((res: any) => {
      console.log(res);
      Cookie.set("token", res.token);
      Cookie.set("expire", new Date(res.end_at).getTime().toString());
      navigate(Path.Chat);
    });
  };
  const resetAccessCode = () => {
    accessStore.update((access) => {
      access.openaiApiKey = "";
      access.accessCode = "";
    });
  }; // Reset access code to empty string

  useEffect(() => {
    if (getClientConfig()?.isApp) {
      navigate(Path.Settings);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className={styles["auth-page"]}>
      <div className={`no-dark ${styles["auth-logo"]}`}>
        <BotIcon />
      </div>

      {/* <div className={styles["auth-title"]}>{Locale.Auth.Title}</div> */}
      {/* <div className={styles["auth-tips"]}>{Locale.Auth.Tips}</div> */}

      <input
        className={styles["auth-input"]}
        type="text"
        placeholder="请输入账户名"
        value={accessStore.user.login_name}
        onChange={(e) => {
          console.log(e);
          accessStore.update(
            (access) => (access.user.login_name = e.currentTarget.value),
          );
        }}
      />
      {!accessStore.hideUserApiKey ? (
        <>
          {/* <div className={styles["auth-tips"]}>{Locale.Auth.SubTips}</div> */}
          <input
            className={styles["auth-input"]}
            type="password"
            placeholder="请输入密码"
            value={accessStore.user.password}
            onChange={(e) => {
              console.log(e);
              accessStore.update(
                (access) => (access.user.password = e.currentTarget.value),
              );
            }}
          />
        </>
      ) : null}

      <div className={styles["auth-actions"]}>
        <IconButton text="登录" type="primary" onClick={goChat} />
        {/* <IconButton
          text={Locale.Auth.Later}
          onClick={() => {
            resetAccessCode();
            goHome();
          }}
        /> */}
      </div>
    </div>
  );
}
